const fs = require('fs'),
  path = require('path')

function listFiles (dir, excludeFn, arr, rootDir) {
  let files = fs.readdirSync(dir, { encoding: 'utf8', withFileTypes: true })
  files = files.filter(file => excludeFn(dir, file)).forEach(file => {
    const filepath = `${dir}/${file.name}`.replace(/\\/g, '/')
    if (isFile(filepath)) {
      arr.push({
        filepath, name: file.name, rootDir
      })
    } else {
      listFiles(filepath, excludeFn, arr, rootDir)
    }
  })
}

function isDir (filepath) {
  let stat = fs.statSync(filepath)
  return stat.isDirectory()
}

function isFile (filepath) {
  let stat = fs.statSync(filepath)
  return stat.isFile()
}

function deleteDir (pathname) {
  let files = []
  if (fs.existsSync(pathname)) {
    files = fs.readdirSync(pathname)
    files.forEach(function (file, index) {
      let curPath = path.join(pathname, file)
      if (fs.statSync(curPath).isDirectory()) {
        deleteDir(curPath)
      } else {
        fs.unlinkSync(curPath)
      }
    })
    fs.rmdirSync(pathname)
  } else {
    console.log('给定的路径不存在！')
  }
}

module.exports = {
  /**
   * 判断是否是文件
   * @param {String} filepath  文件路径
   * @returns Boolean
   */
  isFile (filepath) {
    return isFile(filepath)
  },
  /**
   * 判断是否是文件夹
   * @param {String} filepath  文件路径
   * @returns Boolean
   */
  isDir (filepath) {
    return isDir(filepath)
  },
  /**
   * 递归遍历所有文件夹和文件
   * @param {String} path              文件目录
   * @param {Function} excludes   排除文件回调函数
   */
  listFiles (dir, excludeFn = function () { return true }) {
    if (!fs.existsSync(dir)) {
      console.info('文件目录不存在')
      return
    }
    const array = []
    listFiles(dir, excludeFn, array, dir.replace(/\\/g, '/'))
    return array
  },
  /**
   * 读取文件内容
   * @param {*} filepath
   * @returns String
   */
  readFile (filepath) {
    return fs.readFileSync(filepath, 'utf8')
  },
  /**
   * 判断文件会文件夹是否存在
   * @param {*} filename
   * @returns Boolean
   */
  isExist (filename) {
    return fs.existsSync(filename)
  },
  /**
   * 创建目录
   * @param {*} dirname
   * @returns
   */
  mkdirs (dirname) {
    if (fs.existsSync(dirname)) {
      return true
    }
    if (this.mkdirs(path.dirname(dirname))) {
      fs.mkdirSync(dirname)
      return true
    }
  },
  /**
   * 递归删除目录
   * @param {*} path
   */
  deleteDir (pathname) {
    deleteDir(pathname)
  },
  writeJSON (filename, json) {
    fs.writeFileSync(filename, JSON.stringify(json, null, 2), 'utf8')
  },
  write (filename, content) {
    fs.writeFileSync(filename, content)
  }
}